// app/schedule/mysqlBackup.js
const Subscription = require('egg').Subscription;
const { exec } = require('child_process');
const path = require('path');
const fs = require('fs');
const moment = require('moment');

class MySQLBackup extends Subscription {
  static get schedule() {
    return {
      // 每天凌晨 3 点执行备份任务
      cron: '0 0 3 * * *', 
      type: 'worker', 
    };
  }

  async subscribe() {
    const { app } = this;
    const { host, port, user, password, database } = app.config.mysql.client;
    const backupDir = path.join(__dirname, '../../../dataBaseBackup');
    // 创建备份目录（如果不存在）
    if (!fs.existsSync(backupDir)) {
      fs.mkdirSync(backupDir);
    }
    // const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    const timestamp = moment(new Date()).format('YYYY-MM-DD')
    const backupFilePath = path.join(backupDir, `${database}-${timestamp}.sql`);

    // 构建 mysqldump 命令
    const command = `mysqldump -h ${host} -P ${port} -u ${user} -p${password} ${database} > ${backupFilePath}`;

    // 执行备份命令
    exec(command, (error, stdout, stderr) => {
      if (error) {
        app.logger.error(`MySQL backup failed: ${error.message}`);
        return;
      }
      if (stderr) {
        app.logger.warn(`MySQL backup stderr: ${stderr}`);
      }
      app.logger.info(`MySQL backup succeeded: ${backupFilePath}`);
    });
  }
}

module.exports = MySQLBackup;